大家好,我是 Yubin
這篇文章介紹 Fastify server 在程式中的實體 (instance),Type 定義在 FastifyInstance。
fastify 模組 default export 的是一個用來產生 FastifyInstance 的 function,可以利用那個 function 來產生 FastifyInstance 物件。
import fastify, { FastifyInstance } from 'fastify'
const server: FastifyInstance = fastify()
用這種方式就可以產生一個 FastifyInstance 出來,就可以開始定義 route,開發 API。
這個 fastify() 的 function 可以帶入一個 FastifyServerOptions 物件來設定這個 server,而不是全部走 default 值。
import fastify, { FastifyInstance, FastifyServerOptions } from 'fastify'
const serverOptions : FastifyServerOptions = {
    logger: true,
    // ...
}
const server: FastifyInstance = fastify(serverOptions)
http2false。true,則使用 HTTP/2 模組來建立 socket。connectionTimeout0 (不設定逾時)。keepAliveTimeout72000 ms (72秒)。maxRequestsPerSocket0 (沒有限制)。requestTimeout0 (沒有限制)。ignoreTrailingSlashfalse,不忽略結尾斜線。/hello 跟 /hello/ 代表不同 Endpoint。ignoreDuplicateSlashesfalse。/api/hello 與 /api//hello 代表同一個 Endpoint。maxParamLength100,定義 route 中參數的最大長度。bodyLimit1048576 (1MiB)。loggerfalse。disableRequestLoggingfalse。true,預設情況下,每個 request 進來、每個 response 出去都會寫 log。false 就不會幫你寫這兩個預設的 log。serverFactorycaseSensitivetrue。/hello 跟 /HELLO 是不同的 Endpoint。false 會違反 RFC3986。requestIdHeaderrequest-id。參考 logging-request-id。false,則 id 產生的方式由 genReqId 決定。requestIdLogLabelreqId。genReqIdrequest-id 的 handler。trustProxyfalse。X-Forwarded-* 的 HTTP Header。pluginTimeout10000 ms (10秒)。return503OnClosingtrue。close 被呼叫的時候,若有 request 進來則回應 503 的狀態碼。rewriteUrlfunction rewriteUrl (req) { // req is the Node.js HTTP request
  return req.url === '/hi' ? '/hello' : req.url;
}
以上更詳細的參數跟介紹可以參考 FastifyServerOptions。